package cc.iotkit.screen.dao;

import cc.iotkit.common.satoken.utils.LoginHelper;
import cc.iotkit.screen.dto.Period;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import java.util.Map;

/***
 * 围栏警告
 */
@Component
public class FenceAlertRepositoryImpl implements FenceAlertRepository{
    @PersistenceContext
    private EntityManager entityManager;

    /**
     *围栏外警告
     * @param minute 分钟数，查询多少分钟内的告警设备数量
     * @return
     */
    public Integer getStatistics(Integer minute){
        int limit=10;
        String sql="select device_id from alert_fence \n" +
                "WHERE create_at>=DATE_SUB(NOW(), INTERVAL "+minute+" MINUTE)\n" +
                "GROUP BY device_id";
        List<Map<String,Object>> result= entityManager.createNativeQuery(sql).unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
                .getResultList();
        return result.size();
    }


    private String tenantPermission(){
        //超级管理员或系统进程调用
        if(LoginHelper.isSuperAdmin()|| RequestContextHolder.getRequestAttributes()==null)
            return "";
        else {
            return " and tenant_id="+LoginHelper.getTenantId();
        }
    }
}
